import React, { Component } from 'react';
import { connect } from 'dva';
import { Form, Button, Card, Input } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

// redux中间件
@connect(state => {
  const {articles: {isSavedSuccess}} = state
  return {isSavedSuccess}
})

class Add extends Component {
  submitHandler = e => {
    e.preventDefault()
    const {validateFields} = this.props.form
    validateFields((err, values) => {
        if(!err) {
            this.props.dispatch({
                type: 'articles/addArticle',
                payload: values
            })
        }
    })
}


  render() {
    const { getFieldDecorator: gfd } = this.props.form;
    const itemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 },
      },
    };
    return (
      <PageHeaderLayout title="添加文章" content="输入文章并保存。">
      {this.props.isSavedSuccess && <h1>保存成功！</h1>}
        <Card bordered={false}>
          <Form onSubmit={this.submitHandler}>
            <Form.Item {...itemLayout} label="标题">
              {gfd('title', {
                rules: [{ required: true, message: '必须输入标题！' }],
              })(<Input />)}
            </Form.Item>
            <Form.Item {...itemLayout} label="正文">
              {gfd('content', {
                rules: [
                  { required: true, message: '必须有正文！' },
                  { min: 10, message: '至少10个字！' },
                ],
              })(<Input.TextArea autosize={{ minRows: 10 }} />)}
            </Form.Item>
            <Form.Item wrapperCol={{ span: 8, offset: 7 }}>
              <Button type="primary" size="large" htmlType="submit">
                保存
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </PageHeaderLayout>
    );
  }
}

export default Form.create()(Add);
